1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package com.google.common.cache;
18
19 import com.google.caliper.BeforeExperiment;
20 import com.google.caliper.Benchmark;
21 import com.google.common.base.Function;
22 import com.google.common.base.Functions;
23 import com.google.common.collect.MapMaker;
24
25 import java.util.Map;
26
27
28
29
30
31
32 public class MapMakerComparisonBenchmark {
33 private static final String TEST_KEY = "test key";
34 private static final String TEST_VALUE = "test value";
35
36 private static final Function<Object, Object> IDENTITY = Functions.identity();
37
38
39 private final Map<Object, Object> computingMap = new MapMaker().makeComputingMap(IDENTITY);
40 private final LoadingCache<Object, Object> loadingCache =
41 CacheBuilder.newBuilder().recordStats().build(CacheLoader.from(IDENTITY));
42 private final LoadingCache<Object, Object> loadingCacheNoStats =
43 CacheBuilder.newBuilder().build(CacheLoader.from(IDENTITY));
44
45
46 private final Map<Object, Object> map = new MapMaker().makeMap();
47 private final Cache<Object, Object> cache = CacheBuilder.newBuilder().recordStats().build();
48 private final Cache<Object, Object> cacheNoStats = CacheBuilder.newBuilder().build();
49
50 @BeforeExperiment
51 void setUp() {
52 map.put(TEST_KEY, TEST_VALUE);
53 cache.put(TEST_KEY, TEST_VALUE);
54 cacheNoStats.put(TEST_KEY, TEST_VALUE);
55 }
56
57 @Benchmark void computingMapMaker(int rep) {
58 for (int i = 0; i < rep; i++) {
59 computingMap.get(TEST_KEY);
60 }
61 }
62
63 @Benchmark void loadingCacheBuilder_stats(int rep) {
64 for (int i = 0; i < rep; i++) {
65 loadingCache.getUnchecked(TEST_KEY);
66 }
67 }
68
69 @Benchmark void loadingCacheBuilder(int rep) {
70 for (int i = 0; i < rep; i++) {
71 loadingCacheNoStats.getUnchecked(TEST_KEY);
72 }
73 }
74
75 @Benchmark void concurrentHashMap(int rep) {
76 for (int i = 0; i < rep; i++) {
77 map.get(TEST_KEY);
78 }
79 }
80
81 @Benchmark void cacheBuilder_stats(int rep) {
82 for (int i = 0; i < rep; i++) {
83 cache.getIfPresent(TEST_KEY);
84 }
85 }
86
87 @Benchmark void cacheBuilder(int rep) {
88 for (int i = 0; i < rep; i++) {
89 cacheNoStats.getIfPresent(TEST_KEY);
90 }
91 }
92 }